<template>
  <div class="edit-page-wrap">
    <Head title="基本信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          class="edit-form-wrap"
        >
          <el-form-item label="任务名称" prop="taskName">
            <el-input
              v-model.trim="ruleForm.taskName"
              placeholder="请输入任务名称"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="生效时间" prop="nextTime">
            <el-date-picker
              v-model="ruleForm.nextTime"
              popper-class="qc-date qc-hour"
              type="datetime"
              placeholder="请选择生效时间"
              valueFormat="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH"
              :disabled-date="disabledDate"
            />
          </el-form-item>
          <el-form-item label="电桩价格类型" prop="priceSet" class="has-tips">
            <el-radio-group
              v-model="ruleForm.priceSet"
              v-for="(item, index) in optionsS.priceSet"
              :key="index"
              @change="handleChangeSet"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
            <div class="tip">
              <div class="icon"></div>
              {{
                ruleForm.priceSet === '1'
                  ? '对所选场站中“按电站定价”的所有电桩统一调价'
                  : '对所选的各场站“单独定价”的电桩进行调价'
              }}
            </div>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.priceSet === '1'"
            label="待调价场站"
            prop="stationIds"
          >
            <QcTree
              ref="treeStationRef"
              :setCheckedKeys="ruleForm.stationIds.split(',')"
              :data="optionsS.station"
              :showCheckbox="true"
              @handleCheck="handleCheckStation"
            ></QcTree>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.priceSet === '2'"
            label="待调价电桩"
            prop="equipmentIds"
          >
            <QcTree
              ref="treePileRef"
              :setCheckedKeys="ruleForm.equipmentIds.split(',')"
              :data="optionsS.pile"
              :showCheckbox="true"
              @handleCheck="handleCheckPile"
            ></QcTree>
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <Head title="计费模板">
      <template #content>
        <el-form
          ref="ruleFormPriceRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          class="edit-form-wrap"
        >
          <el-form-item
            v-for="(item, index) in optionsS.version"
            :key="item.value"
            :label="`协议${item.label}`"
          >
            <qc-select
              :value="ruleForm.templates[index].tId"
              :remote="true"
              :filterable="true"
              :options="ruleForm.templates[index].list"
              placeholder="请选择计费模板"
              @change="handleChangeTemplate($event, item, index)"
              @visible-change="handleVisibleTemplate($event, item, index)"
            >
            </qc-select>
            <el-button
              type="primary"
              @click="clickTemplate(index)"
              :disabled="!ruleForm.templates[index].tId"
              class="item-btn"
              >查看计费</el-button
            >
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
    <DialogPrice ref="dialogPriceRef"></DialogPrice>
  </div>
</template>


<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus';
import Head from '@/components/head/index.vue';
import QcTree from '@/components/qcTree/index.vue';
import DialogPrice from '../components/dialogPrice.vue';
import { queryDicByParent } from '@/service/apis/api';
import {
  stationTreeDataByChannel,
  equipmentTreeData,
} from '@/service/apis/org';
import {
  queryCostTemplateByProtocolVersion,
  addStationTaskTransferPrice,
  updateStationTaskTransferPrice,
  queryStationTaskTransferPrice,
} from '@/service/apis/pile';

const router = useRouter();
const route = useRoute();
const {
  query: { id },
} = route;

const ruleFormRef = ref<FormInstance>();
const ruleFormPriceRef = ref<FormInstance>();
const dialogPriceRef = ref();
const treeStationRef = ref();
const treePileRef = ref();

let optionsS = reactive({
  version: [] as any,
  priceSet: [] as any,
  station: [] as any,
  pile: [] as any,
});

queryDicByParent({
  listDtos: ['priceSet', 'protocolVersion'],
}).then((res: any) => {
  if (res) {
    optionsS.priceSet = res.priceSet;
    optionsS.version = res.protocolVersion;
    ruleForm.templates = [];
    optionsS.version.forEach((item: any) => {
      ruleForm.templates.push({
        vName: item.label,
        vId: item.value,
        tId: undefined as any,
        list: [] as any,
      });
    });
    // 计费模板回填
    setTemplates();
  }
});

// 获取电站树
const getStations = () => {
  stationTreeDataByChannel({}).then((res: any) => {
    if (res) {
      console.log('res---', res);
      optionsS.station = res;
    }
  });
};

// 获取电桩树
const getPlies = () => {
  equipmentTreeData({}).then((res: any) => {
    if (res) {
      console.log('res---', res);
      optionsS.pile = res;
    }
  });
};

let ruleForm: any = reactive({
  id: id,
  taskName: '', //任务名称
  nextTime: '', // 生效时间
  priceSet: '1', //电桩价格类型
  stationIds: '', // 待调价场站
  equipmentIds: '', //待调价电桩
  templates: [] as any, // 计费模板数据-前端使用
  stationTaskTransferPriceInfoList: [] as any,
});

const disabledDate = (time: any) => {
  return time.getTime() < new Date(new Date().toLocaleDateString()).getTime();
};
const checkTime = (rule: any, value: any, callback: any) => {
  if (new Date(value).getTime() < new Date().getTime()) {
    callback(new Error('生效时间不能小于于当前时间'));
  }
  callback();
};
const rules = reactive<FormRules>({
  taskName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
  nextTime: [
    { required: true, message: '请选择生效时间', trigger: ['blur', 'change'] },
    { validator: checkTime, trigger: ['blur', 'change'] },
  ],
  priceSet: [
    {
      required: true,
      message: '请选择电桩价格类型',
      trigger: ['blur', 'change'],
    },
  ],
  stationIds: [
    {
      required: true,
      message: '请选择待调价场站',
      trigger: ['blur', 'change'],
    },
  ],
  equipmentIds: [
    {
      required: true,
      message: '请选择待调价电桩',
      trigger: ['blur', 'change'],
    },
  ],
});

const handleChangeSet = (val: any) => {
  if (val === '1' && optionsS.station.length === 0) {
    getStations();
  } else if (val === '2' && optionsS.pile.length === 0) {
    getPlies();
  }
};

const handleCheckStation = (
  data: any,
  checkedData: any,
  checkedChildData: any
) => {
  ruleForm.stationIds = checkedChildData.toString();
  console.log(ruleForm.stationIds);
  ruleFormRef.value?.validateField('stationIds');
};
const handleCheckPile = (
  data: any,
  checkedData: any,
  checkedChildData: any
) => {
  ruleForm.equipmentIds = checkedChildData.toString();
  console.log(ruleForm.equipmentIds);
  ruleFormRef.value?.validateField('equipmentIds');
};

const getCostTemplate = (val: any) => {
  return new Promise((resolve) => {
    queryCostTemplateByProtocolVersion({ value: val }).then((res: any) => {
      if (res) {
        resolve([...res.list]);
      }
    });
  });
};
const handleVisibleTemplate = async (e: any, item: any, index: number) => {
  if (e) {
    const temp = ruleForm.templates[index];
    if (temp.list.length === 0) {
      temp.list = await getCostTemplate(temp.vId);
    }
  }
};
const handleChangeTemplate = (e: any, item: any, index: number) => {
  console.log(e, item, index);
  ruleForm.templates[index].tId = e;
};

const clickTemplate = (index: number) => {
  dialogPriceRef.value?.show(ruleForm.templates[index].tId);
};

if (id) {
  queryStationTaskTransferPrice({ id: id }).then((res: any) => {
    if (res) {
      for (const key in ruleForm) {
        if (res[key]) {
          ruleForm[key] = res[key];
        }
      }
      // 树数据
      if (ruleForm.priceSet === '2') {
        getPlies();
      } else {
        getStations();
      }
      // 计费模板回填
      setTemplates();
    }
  });
} else {
  getStations();
}

const setTemplates = () => {
  const list = ruleForm.stationTaskTransferPriceInfoList;
  const temp = ruleForm.templates;
  console.log();
  if (list?.length > 0 && list.length === temp.length) {
    list.forEach(async (item: any, index: number) => {
      temp[index].tId = item.costTemplateId;
      temp[index].list = await getCostTemplate(item.protocolVersionId);
    });
  }
};

const back = () => {
  router.go(-1);
};

const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  if (!ruleFormRef.value || !ruleFormPriceRef.value) return;
  let flag = true;
  let objError = {} as any;
  await Promise.all([
    ruleFormRef.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
    ruleFormPriceRef.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
  ]);
  if (!flag) {
    for (const key in ruleForm) {
      if (objError[key]) {
        ruleFormRef.value.scrollToField(key);
        ruleFormPriceRef.value.scrollToField(key);
        break;
      }
    }
    return;
  }
  //计费模板
  ruleForm.stationTaskTransferPriceInfoList = ruleForm.templates.map(
    (item: any) => ({
      protocolVersionId: item.vId,
      costTemplateId: item.tId,
    })
  );
  console.log('ru---', ruleForm);
  ruleForm.nextTime = ruleForm.nextTime.substring(0, 13) + ':00:00';
  if (id) {
    updateStationTaskTransferPrice(ruleForm).then((res: any) => {
      emit('clear-cache');
      back();
    });
  } else {
    addStationTaskTransferPrice(ruleForm).then((res: any) => {
      emit('clear-cache');
      back();
    });
  }
};
</script>